<template>
  <van-form @submit="onSubmit" label-align="top" class="formGroup">
    <van-cell-group inset>
      <van-field
        v-model="form.title"
        readonly
        label="比赛名称"
        placeholder="比赛名称"
      />
    </van-cell-group>
    <van-divider />
    <van-cell-group inset v-if="info.includes('1')">
      <van-field
        v-model="form.name"
        label="参赛者姓名"
        placeholder="填写参赛者姓名"
        :rules="[{ required: true, message: '请填写参赛者姓名' }]"
      />
    </van-cell-group>
    <van-cell-group inset v-if="info.includes('2')">
      <van-field
        v-model="form.date"
        is-link
        readonly
        name="picker"
        label="参赛者生日"
        placeholder="点击选择参赛者生日"
        @click="showPicker = true"
      />
      <van-popup v-model:show="showPicker" position="bottom">
        <van-date-picker
          v-model="currentDate"
          title="选择日期"
          :min-date="minDate"
          :max-date="maxDate"
          @confirm="onConfirm"
          @cancel="showPicker = false"
        />
      </van-popup>
    </van-cell-group>
    <van-cell-group inset v-if="info.includes('3')">
      <van-field name="radio" label="性别">
        <template #input>
          <van-radio-group v-model="form.sex" direction="horizontal">
            <van-radio :name="1">男</van-radio>
            <van-radio :name="2">女</van-radio>
          </van-radio-group>
        </template>
      </van-field>
    </van-cell-group>
    <van-cell-group inset v-if="info.includes('4')">
      <van-field
        v-model="form.card"
        label="参赛者身份证号"
        placeholder="填写参赛者身份证号"
        label-align="top"
        :rules="[{ required: true, message: '请填写参赛者身份证号' }]"
      />
    </van-cell-group>
    <van-cell-group inset v-if="info.includes('5')">
      <van-field
        v-model="form.phone"
        label="参赛者联系电话"
        placeholder="填写参赛者联系电话"
        label-align="top"
        :rules="[{ required: true, message: '请填写参赛者联系电话' }]"
      />
    </van-cell-group>
    <van-cell-group inset v-if="info.includes('6')">
      <van-field name="uploader" label="参赛者认证证书">
        <template #input>
          <van-uploader
            v-model="form.imgList"
            :max-count="6"
            :after-read="handleAfterRead"
            accept="image/*"
          />
        </template>
      </van-field>
    </van-cell-group>
    <div class="toastImg" v-if="info.includes('6')">最多上传6张，最少1张</div>
    <van-cell-group inset v-if="info.includes('7')">
      <van-field
        v-model="form.bm_name"
        label="报名人姓名"
        placeholder="填写报名人姓名"
        :rules="[{ required: true, message: '请填写报名人姓名' }]"
      />
    </van-cell-group>
    <van-cell-group inset v-if="info.includes('8')">
      <van-field
        v-model="form.bm_mobile"
        label="报名人联系电话"
        placeholder="填写报名人联系电话"
        :rules="[{ required: true, message: '请填写报报名人联系电话' }]"
      />
    </van-cell-group>
    <van-cell-group inset v-if="info.includes('9')">
      <!-- <van-field
        v-model="form.group"
        label="组别"
        placeholder="填写组别"
        :rules="[{ required: true, message: '请填写组别' }]"
      /> -->
      <van-field
        v-model="groupFieldValue"
        is-link
        readonly
        name="picker"
        label="组别"
        placeholder="点击选择组别"
        @click="showGroupPicker = true"
      />
      <van-popup v-model:show="showGroupPicker" position="bottom">
        <van-picker
          title="组别"
          :columns="columns"
          @confirm="onGroupConfirm"
          @cancel="showGroupPicker = false"
          :model-value="[form.group_id]"
        />
      </van-popup>
    </van-cell-group>
    <van-divider />
    <van-cell-group inset class="pd-20 amount">
      <div class="payTitle">支付报名金额</div>
      <div class="payNum">金额：{{ amount }}</div>
    </van-cell-group>
    <van-cell-group inset class="pd-20 tijiBtn" v-if="sis">
      <!-- <van-button round block type="primary" native-type="submit">
        提交
      </van-button> -->
      <div class="subscribe-btn" @click="onSubmit">提交</div>
    </van-cell-group>
    <van-cell-group inset class="pd-20 tijiBtn" v-else>
      <wx-open-subscribe
        template="9M-v4bb-i8Vn0J-Xe0mpBsBxjvU1BT7GBzUPxfknrGA"
        id="subscribe-btn"
      >
        <component :is="'script'" type="text/wxtag-template">
          <div
            style="
              width: 100%;
              display: flex;
              justify-content: center;
              align-items: center;
              padding: 6px 0 10px 0;
              background: #1989fa;
              border-radius: 4px;
              color: #fff;
              font-size: 7px;
            "
          >
            提交
          </div>
        </component>
      </wx-open-subscribe>
    </van-cell-group>
  </van-form>
  <van-dialog width="80%" v-model:show="showDialog" :showConfirmButton="false">
    <div class="payDialog">
      <van-icon
        name="close"
        class="dialogClose"
        size="18px"
        @click="showDialog = false"
      />
      <div class="dialogTitle">费用支付</div>
      <div class="dialogNum">金额：{{ amount }}</div>
      <div class="dialogRadio">
        <van-radio-group v-model="payType">
          <van-radio :name="1">微信支付</van-radio>
          <van-radio :name="2" v-if="route.query.ISXY == 'Y'"
            >兴业银行</van-radio
          >
        </van-radio-group>
        <div class="info" v-if="route.query.ISXY == 'Y'">
          绑定兴业银行信用卡，免费报名
        </div>
      </div>
      <div class="dialogBtn">
        <van-button round block type="primary" @click="payFn">
          支付
        </van-button>
      </div>
    </div>
  </van-dialog>
</template>
<script setup>
import { appid, domainUrl } from "@/utils/appInfo";
import { ref, onMounted } from "vue";
import { saveStorage, getStorage } from "@/utils/storage";
import service from "@/http";
import axios from "axios";
// import wx from "weixin-jsapi";
import { useRoute, useRouter } from "vue-router";
import { showToast, showSuccessToast } from "vant";
import imageCompression from "browser-image-compression";

const route = useRoute();
const router = useRouter();

const showPicker = ref(false);
const minDate = ref(new Date(1900, 1, 1));
const maxDate = ref(new Date());
const currentDate = ref(["1999", "01", "01"]);

const showGroupPicker = ref(false);
const groupFieldValue = ref("");
const columns = ref([]);

const amount = ref();
const hasXY = ref(false);
const info = ref([]);

const payType = ref(1);
const payLoading = ref(false);

const sis = ref(false);

const form = ref({
  title: "",
  name: "",
  sex: 1,
  date: "",
  card: "",
  phone: "",
  imgList: [],
  bm_name: "",
  bm_mobile: "",
  group_id: "",
});

const showDialog = ref(false);

const vaildToken = () => {
  service
    .post("/api/h5/user/heart")
    .then((response) => {
      const data = response.data;
      if (data.code == 20000) {
        setQueryData();
      }
    })
    .catch((error) => {
      console.error(error);
    });
};

const getToken = () => {
  debugger;
  // 获取token
  const token = getStorage("token");
  console.log(
    "%c [ route ]-224",
    "font-size:13px; background:#93926f; color:#d7d6b3;",
    route
  );
  const code = route.query.code;
  if (token) {
    // 登录
    vaildToken();
  } else {
    if (!code) {
      // 未登录
      const redirectUrl = new URL(domainUrl);
      Object.entries(route.query).forEach(([key, value]) => {
        redirectUrl.searchParams.append(key, value);
      });
      const fullUrl = redirectUrl.toString();
      let url = encodeURIComponent(fullUrl);
      window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${url}&response_type=code&scope=snsapi_base&state=123#wechat_redirect`;
    } else {
      service
        .post("/api/h5/user/login", { code: code })
        .then((response) => {
          const data = response.data;
          if (data.code == 20000) {
            saveStorage("token", data.data.token);
            setQueryData();
          }
        })
        .catch((error) => {
          console.error(error);
        });
    }
  }
};

const getSubscribe = () => {
  service
    .post("/api/h5/notice/sis_subscribe")
    .then((response) => {
      const data = response.data;
      if (data.code == 20000) {
        console.log(data.data);
        sis.value = data.data.sis;
      }
    })
    .catch((error) => {
      console.error(error);
    });
};

const setQueryData = () => {
  getSubscribe();
  form.value.title = route.query.Name;
  amount.value = route.query.Fee;
  info.value = route.query.Info ? route.query.Info.split(",") : [];
  hasXY.value = route.query.ISXY == "Y" ? true : false;
  getWXConfig();
};

const onConfirm = (data) => {
  console.log(
    "%c [ data ]-313",
    "font-size:13px; background:#c79554; color:#ffd998;",
    data
  );
  form.value.date = data.selectedValues.join("-");
  showPicker.value = false;
};

const getGroupList = () => {
  service.get("/api/h5/registrate/group").then((response) => {
    const data = response.data;
    if (data.code == 20000) {
      columns.value = Object.entries(data.data).map(([key, value]) => ({
        value: key,
        text: value,
      }));
    }
  });
};

const onGroupConfirm = (data) => {
  console.log(
    "%c [ data ]-334",
    "font-size:13px; background:#1da9e7; color:#61edff;",
    data
  );
  groupFieldValue.value = data.selectedOptions[0].text;
  form.value.group_id = data.selectedValues[0];
  showGroupPicker.value = false;
};

const handleAfterRead = async (file) => {
  // const res = await uploadFile(file);
  // // 上传成功后处理结果
  // if (file instanceof Array) {
  //   file.forEach((item, index) => {
  //     item.status = "success";
  //     item.url = res.data.data[index];
  //   });
  // } else {
  //   file.status = "success";
  //   file.url = res.data.data;
  // }

  // 压缩图片的选项
  const options = {
    maxSizeMB: 1, // 最大文件大小 (MB)
    maxWidthOrHeight: 800, // 最大宽度或高度
    useWebWorker: true, // 使用 Web Worker
  };

  try {
    // 压缩单个文件
    const compressedFile = await imageCompression(file.file, options);
    file.file = compressedFile;
    // 模拟接口调用
    const res = await uploadFile(file);

    // 上传成功后处理结果
    file.status = "success"; // 设置上传状态
    file.url = res.data.data; // 假设 res.data.data 是上传后返回的 URL
  } catch (error) {
    console.error("压缩或上传失败:", error);
    const res = await uploadFile(file);
    file.status = "success"; // 设置上传状态
    file.url = res.data.data; // 假设 res.data.data 是上传后返回的 URL
  }
};

const uploadFile = (file) => {
  // 创建 FormData 对象
  const formData = new FormData();
  formData.append("file", file.file); // 将文件添加到 FormData
  return axios.post("/api/h5/file/upload", formData, {
    headers: {
      "Content-Type": "multipart/form-data",
    },
  });
};
const payFn = () => {
  if (payLoading.value) {
    return;
  }
  const imgArr = form.value.imgList.map((item) => item.url);
  const param = {
    name: form.value.title,
    info: route.query.Info,
    isxy: route.query.ISXY,
    user_name: form.value.name,
    sex: form.value.sex,
    birthday: form.value.date,
    id_no: form.value.card,
    mobile: form.value.phone,
    bm_name: form.value.bm_name,
    bm_mobile: form.value.bm_mobile,
    group_id: form.value.group_id,
    fee: amount.value,
    certificate: imgArr,
    pay_type: payType.value == 2 ? "xy_bank" : "wechat",
  };
  payLoading.value = true;
  service
    .post("/api/h5/registrate/commit", param)
    .then((response) => {
      const data = response.data;
      if (data.code == 20000) {
        if (payType.value == 2) {
        } else {
          // wxPayFc(data.data);
          wxPay(data.data);
        }
      }
    })
    .catch((error) => {
      console.log(error);
    })
    .finally(() => {
      payLoading.value = false;
    });
};

const onSubmit = () => {
  // 提交表单
  console.log("提交表单", form.value);
  if (info.value.includes("2") && !form.value.date) {
    showToast({ message: "请选择参赛者生日" });
    return;
  }
  const cardRegex =
    /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
  if (info.value.includes("4") && !cardRegex.test(form.value.card)) {
    showToast({ message: "请填写正确的参赛者身份证号" });
    return;
  }

  const phoneRegex = /^1[3-9]\d{9}$/;
  if (info.value.includes("5") && !phoneRegex.test(form.value.phone)) {
    showToast({ message: "请填写正确的参赛者联系电话" });
    return;
  }
  if (info.value.includes("8") && !phoneRegex.test(form.value.bm_mobile)) {
    showToast({ message: "请填写正确的报名人联系电话" });
    return;
  }
  if (info.value.includes("6") && !form.value.imgList.length) {
    showToast({ message: "请上传参赛者认证证书" });
    return;
  }
  if (info.value.includes("9") && !form.value.group_id) {
    showToast({ message: "请选择组别" });
    return;
  }
  // if (route.query.ISXY == "Y") {
  //   payType.value = 1;
  //   showDialog.value = true;
  // } else {
  //   payFn();
  // }
  payType.value = 1;
  showDialog.value = true;
};

// 这个方法需要在提交订单的时候拼接url 获取签名信息参数 （或者单独请求返回也行）
// const wxPayFc = (body) => {
//   // const url = window.location.href.split('#')[0]; // 获取当前页面的完整 URL
//   // const { sign } = await getSignature(url); // 从后端获取签名信息
//   wx.config({
//     debug: true, // 这里一般在测试阶段先用ture，等打包给后台的时候就改回false,
//     appId: appid, //公众号ID，由商户传入
//     timeStamp: body.timestamp, //时间戳，自1970年以来的秒数
//     nonceStr: body.nonceStr, // 必填，生成签名的随机串
//     signature: body.paySign, // 必填，签名
//     jsApiList: ["chooseWXPay", "checkJsApi"], // 必填，需要使用的JS接口列表
//   });
//   wx.ready(() => {
//     // wx.checkJsApi({
//     //   jsApiList: ['chooseWXPay'],
//     //   success:function(res){},
//     //   fail:function(res){}})
//     wx.chooseWXPay({
//       timeStamp: body.timestamp, //时间戳，自1970年以来的秒数
//       nonceStr: body.nonceStr, // 支付签名随机串，不长于 32 位
//       package: body.package,
//       signType: body.signType, //微信签名方式：
//       paySign: body.paySign, //微信签名
//       success: function (payRes) {
//         // 支付成功后的回调函数
//         showToast({ message: "支付成功" });
//       },
//       cancel: function (payRes) {
//         showToast({ message: "取消支付" });
//       },
//       fail: function (payRes) {
//         showToast({ message: "支付失败" });
//       },
//     });
//   });
// };

const wxPay = (params) => {
  if (typeof WeixinJSBridge == "undefined") {
    if (document.addEventListener) {
      document.addEventListener(
        "WeixinJSBridgeReady",
        onBridgeReady(params),
        false
      );
    } else if (document.attachEvent) {
      document.attachEvent("WeixinJSBridgeReady", onBridgeReady(params));
      document.attachEvent("onWeixinJSBridgeReady", onBridgeReady(params));
    }
  } else {
    onBridgeReady(params);
  }
};

const refreshRoute = () => {
  form.value = {
    title: "",
    name: "",
    sex: 1,
    date: "",
    card: "",
    phone: "",
    imgList: [],
    bm_name: "",
    bm_mobile: "",
    group_id: "",
  };
  showDialog.value = false;
  // 获取当前路由的路径
  const currentPath = route.path;
  // 获取当前查询参数
  const currentQuery = route.query;

  // 使用 router.replace 刷新当前路由
  router.replace({ path: currentPath, query: currentQuery });
};

const onBridgeReady = (params) => {
  WeixinJSBridge.invoke(
    "getBrandWCPayRequest",
    {
      appId: appid, //公众号ID，由商户传入
      timeStamp: params.timestamp, //时间戳，自1970年以来的秒数
      nonceStr: params.nonceStr, //随机串
      package: params.package,
      signType: params.signType, //微信签名方式：
      paySign: params.paySign, //微信签名
    },
    function (payResult) {
      if (payResult.err_msg == "get_brand_wcpay_request:ok") {
        console.log("支付成功");
        // 使用以上方式判断前端返回,微信团队郑重提示：
        //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
        showSuccessToast({ message: "支付成功", className: "text-success" });
        setTimeout(function () {
          refreshRoute();
        }, 2000);
      } else if (payResult.err_msg == "get_brand_wcpay_request:cancel") {
        showToast({ message: "支付取消" });
      } else if (payResult.err_msg == "get_brand_wcpay_request:fail") {
        showToast({ message: "支付失败" });
      } else {
        showToast({ message: "未知错误" });
      }
    }
  );
};

const setSubscribe = () => {
  service
    .post("/api/h5/notice/subscribe")
    .then((response) => {
      const data = response.data;
      if (data.code == 20000) {
        console.log(data.data);
        sis.value = true;
      }
    })
    .catch((error) => {
      console.error(error);
    });
};

const subscribeFn = async (data) => {
  console.log(
    "%c [ data ]-509",
    "font-size:13px; background:#a464cb; color:#e8a8ff;",
    data
  );
  wx.config({
    debug: false,
    appId: appid,
    timestamp: data.timestamp,
    nonceStr: data.nonceStr,
    signature: data.signature,
    jsApiList: ["checkJsApi"],
    openTagList: ["wx-open-subscribe"],
  });
  let btn = document.getElementById("subscribe-btn");
  wx.ready(() => {
    console.log("微信 SDK 初始化成功");
    btn.addEventListener("success", function (e) {
      console.log("success", e.detail);
      console.log(
        "%c [ e ]-543",
        "font-size:13px; background:#439fc3; color:#87e3ff;",
        e
      );
      if (e.detail.errMsg == "subscribe:ok") {
        let status = JSON.parse(e.detail.subscribeDetails);
        console.log(
          "%c [ e.detail.subscribeDetails ]-537",
          "font-size:13px; background:#af18eb; color:#f35cff;",
          e.detail.subscribeDetails
        );
        console.log(
          "%c [ status ]-537",
          "font-size:13px; background:#d6922f; color:#ffd673;",
          status
        );
        if (
          JSON.parse(status["9M-v4bb-i8Vn0J-Xe0mpBsBxjvU1BT7GBzUPxfknrGA"])
            .status == "accept"
        ) {
          showToast("订阅成功");
          setSubscribe();
        } else {
          showToast("订阅失败");
        }
      }
      onSubmit();
    });
    btn.addEventListener("error", function (e) {
      console.log("fail", e.detail);
      console.log(
        "%c [ e ]-549",
        "font-size:13px; background:#c5ec31; color:#ffff75;",
        e
      );
      onSubmit();
    });
  });
};

const getWXConfig = () => {
  const url = window.location.href.split("#")[0]; // 获取当前页面的完整 URL
  console.log(
    "%c [ url ]-490",
    "font-size:13px; background:#85d4eb; color:#c9ffff;",
    url
  );
  service.post("/api/h5/notice/init", { url: url }).then((res) => {
    console.log(
      "%c [ res ]-500",
      "font-size:13px; background:#0a7e6c; color:#4ec2b0;",
      res
    );
    const { data } = res;
    if (data.code == 20000) {
      // console.log(res.data);
      subscribeFn(data.data);
    }
  });
};

// const onSuccess = (e) => {
//   console.log(
//     "%c [ e ]-534",
//     "font-size:13px; background:#dd25bb; color:#ff69ff;",
//     e
//   );
//   if (e.detail.errMsg == "subscribe:ok") {
//     let status = JSON.parse(e.detail.subscribeDetails);
//     console.log(
//       "%c [ e.detail.subscribeDetails ]-537",
//       "font-size:13px; background:#af18eb; color:#f35cff;",
//       e.detail.subscribeDetails
//     );
//     console.log(
//       "%c [ status ]-537",
//       "font-size:13px; background:#d6922f; color:#ffd673;",
//       status
//     );
//     if (
//       JSON.parse(status["9M-v4bb-i8Vn0J-Xe0mpBsBxjvU1BT7GBzUPxfknrGA"])
//         .status == "accept"
//     ) {
//       showToast("订阅成功");
//     } else {
//       showToast("订阅失败");
//     }
//     onSubmit();
//   } else {
//     showToast("订阅失败");
//   }
// };

// const onError = (e) => {
//   console.log(e);
//   showToast("订阅失败");
// };

onMounted(() => {
  getToken();
  if (route.query.Info.includes("9")) {
    getGroupList();
  }
});
</script>
<style scoped>
.payTitle {
  font-size: 25px;
}
.payNum {
  font-size: 30px;
  color: #20e472;
  text-align: right;
  margin-left: 40px;
}
.amount {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}
.payDialog {
  padding: 20px;
  position: relative;
}
.dialogTitle {
  text-align: center;
  margin: 20px 0;
  font-size: 30px;
}
.dialogNum {
  text-align: center;
  margin: 20px 0;
  color: #e64340;
  font-size: 35px;
}
.dialogRadio {
  margin: 20px 0;
}
.dialogRadio .van-radio {
  margin: 20px 0;
}
.dialogBtn {
  margin: 40px 0;
}
.info {
  padding-left: 28px;
  font-size: 20px;
}
.dialogClose {
  position: absolute;
  right: 20px;
  top: 20px;
}
.pd-40 {
  padding: 10px 20px;
}
.formGroup {
  padding-top: 20px;
}
.toastImg {
  font-size: 20px;
  padding: 0 40px;
  color: #ccc;
}
.tijiBtn {
  margin-bottom: 40px;
}
#subscribe-btn {
  display: block;
  width: 100%;
}
.subscribe-btn {
  text-align: center;
  background: #1989fa;
  border-radius: 8px;
  color: #fff;
  width: 100%;
  height: 40px;
  line-height: 40px;
  font-size: 14px;
}
</style>
